package com.shqcjd.preinstallmobile.ui.fragment.mine;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.GuideListBean;
import com.shqcjd.preinstallmobile.ui.activity.HistoryGuideFileActivity;
import com.shqcjd.preinstallmobile.ui.adapter.RemoteGuideHistoryAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseFragment;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.SpacesItemDecoration;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.util.UIUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * 远程指导记录
 * Created by sy on 2019/3/22.
 */

public class RemoteGuideHistoryFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener{
    private static final int PAGE_SIZE = 6;
    private int mNextRequestPage = 1;

    @BindView(R.id.rv_inspection_list)
    RecyclerView rvInspectionList;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;

    List<GuideListBean.ItemsBean> guideList = new ArrayList<>();
    private RemoteGuideHistoryAdapter guideHistoryAdapter;
    private View notDataView;

    public static RemoteGuideHistoryFragment newInstance() {
        return new RemoteGuideHistoryFragment();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_wait_inspection;
    }

    @Override
    public void initView(View rootView) {
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvInspectionList.getParent(), false);
        initInspectionList();
        swipeRefresh.setOnRefreshListener(this);
        guideHistoryAdapter.setOnLoadMoreListener(this,rvInspectionList);
    }

    @Override
    public void initData() {
        refresh();
    }


    private void initInspectionList() {
        guideHistoryAdapter = new RemoteGuideHistoryAdapter(guideList);
        rvInspectionList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvInspectionList.addItemDecoration(new SpacesItemDecoration(UIUtils.dip2px(10), UIUtils.dip2px(9)));
        rvInspectionList.setAdapter(guideHistoryAdapter);
        guideHistoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GuideListBean.ItemsBean item = (GuideListBean.ItemsBean) adapter.getItem(position);
                Intent intent = new Intent(getContext(), HistoryGuideFileActivity.class);
                intent.putExtra("GuideID", item.remoteGuideId);
                startActivity(intent);
            }
        });
    }

    /**
     * 刷新数据
     */
    @Override
    public void onRefresh() {
        refresh();
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void refresh(){
        mNextRequestPage = 1;
        //这里的作用是防止下拉刷新的时候还可以上拉加载
        guideHistoryAdapter.setEnableLoadMore(false);
        Map<String, Integer> map = new HashMap<>();
        map.put("pageIndex", mNextRequestPage);
        map.put("pageSize", PAGE_SIZE);
        ApiService.getGuideList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<GuideListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showRefreshView(true);
                    }

                    @Override
                    public void _onNext(ResponseData<GuideListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            setData(true, retData.data.list);
                        } else {
                            ToastUtils.showShort(getContext(), retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        guideHistoryAdapter.setEnableLoadMore(true);
                        showRefreshView(false);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        guideHistoryAdapter.setEnableLoadMore(true);
                        showRefreshView(false);
                    }
                });

    }

    private void loadMore(){
        Map<String, Integer> map = new HashMap<>();
        map.put("pageIndex", mNextRequestPage);
        map.put("pageSize", PAGE_SIZE);
        ApiService.getGuideList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<GuideListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<GuideListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.list);
                        } else {
                            ToastUtils.showShort(getContext(), retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        guideHistoryAdapter.loadMoreFail();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    public void showRefreshView(Boolean refresh) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refresh);
            }
        });
    }

    private void setData(boolean isRefresh, List data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                guideHistoryAdapter.setNewData(data);
            } else {
                guideHistoryAdapter.setNewData(null);
                guideHistoryAdapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                guideHistoryAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            guideHistoryAdapter.loadMoreEnd(isRefresh);
        } else {
            guideHistoryAdapter.loadMoreComplete();
        }
    }
}
